package auth

import (
	"github.com/gin-gonic/gin"
	"scaffold-demo-go/config"
	"scaffold-demo-go/utils/jwtauth"
	"scaffold-demo-go/utils/logs"
)

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 登录逻辑
func Login(c *gin.Context) {
	// 1.获取前端传递用户名和密码
	userInfo := UserInfo{}
	returnData := config.NewReturnData()
	if err := c.ShouldBindJSON(&userInfo); err != nil {
		returnData.Status = 401
		returnData.Message = err.Error()
		c.JSON(200, returnData)
		return
	}
	logs.Deubg(map[string]interface{}{"用户名": userInfo.Username, "密码": userInfo.Password}, "输入的用户名+密码")
	//TODO 修改为读取数据库判断
	// 验证用户名和密码是否正常
	logs.Deubg(map[string]interface{}{"配置的用户名:": config.Username, "密码": config.Password}, "")
	if userInfo.Username == config.Username && userInfo.Password == config.Password {
		// 认证成功 生成JWT的Token
		token, err := jwtauth.GenToken(userInfo.Username)
		if err != nil {
			logs.Error(map[string]interface{}{"用户名": userInfo.Username, "错误信息": err}, "用户密码正确，但生成token失败")
			returnData.Status = 401
			returnData.Message = "生成token失败"
			c.JSON(200, returnData)
			return
		}
		// token正常生成，返回给前端
		logs.Info(map[string]interface{}{"用户名": userInfo.Username}, "登录成功")
		returnData.Status = 200
		returnData.Message = "登录成功"
		returnData.Data["token"] = token
		c.JSON(200, returnData)
		return
	} else {
		// 用户名密码错误
		returnData.Status = 401
		returnData.Message = "账号或密码不对"
		c.JSON(200, returnData)
		return
	}
}

// 退出的逻辑
func Logout(c *gin.Context) {
	returnData := config.NewReturnData()
	returnData.Message = "退出成功"
	c.JSON(200, returnData)
	logs.Deubg(nil, "用户已退出")
}
